<template>
  <div class="my-presentation-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="title">我的发表</h1>
        <p class="subtitle">管理你发布的帖子</p>
      </div>
      <el-button type="primary" size="large" @click="goToPublish">
          <el-icon><Plus /></el-icon>
          发布新帖子
        </el-button>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :xs="12" :sm="6">
          <el-card class="stat-card">
            <div class="stat-content">
            <el-icon class="stat-icon" color="#409eff"><Document /></el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalPosts }}</div>
              <div class="stat-label">总帖子数</div>
            </div>
            </div>
          </el-card>
        </el-col>
      <el-col :xs="12" :sm="6">
          <el-card class="stat-card">
            <div class="stat-content">
            <el-icon class="stat-icon" color="#67c23a"><View /></el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalViews }}</div>
              <div class="stat-label">总浏览数</div>
            </div>
            </div>
          </el-card>
        </el-col>
      <el-col :xs="12" :sm="6">
          <el-card class="stat-card">
            <div class="stat-content">
            <el-icon class="stat-icon" color="#f56c6c"><Star /></el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalLikes }}</div>
              <div class="stat-label">总点赞数</div>
            </div>
            </div>
          </el-card>
        </el-col>
      <el-col :xs="12" :sm="6">
          <el-card class="stat-card">
            <div class="stat-content">
            <el-icon class="stat-icon" color="#e6a23c"><ChatDotRound /></el-icon>
            <div class="stat-info">
              <div class="stat-number">{{ stats.totalComments }}</div>
              <div class="stat-label">总评论数</div>
            </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="8">
          <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option label="钓鱼经验" value="fishing" />
            <el-option label="求助问答" value="help" />
            <el-option label="技巧分享" value="tips" />
            <el-option label="综合讨论" value="general" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="16">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索我的帖子..."
            clearable
            @keyup.enter="handleFilter"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleFilter">搜索</el-button>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 帖子列表 -->
    <div class="posts-section" v-loading="loading">
      <div v-if="posts.length === 0" class="empty-state">
        <el-empty description="暂无帖子数据" />
    </div>

      <el-card v-for="post in posts" :key="post.id" class="post-item" shadow="hover">
        <div class="post-main">
          <div class="post-info">
            <h3 class="post-title" @click="viewPost(post.id)">{{ post.title }}</h3>
            <p class="post-content">{{ post.content.substring(0, 150) }}{{ post.content.length > 150 ? '...' : '' }}</p>
            
            <!-- 图片缩略图 -->
            <div v-if="getImageList(post.images).length > 0" class="post-thumbnails">
              <el-image
                v-for="(img, index) in getImageList(post.images).slice(0, 3)"
                :key="index"
                :src="img"
                :preview-src-list="getImageList(post.images)"
                fit="cover"
                class="thumbnail"
                :preview-teleported="true"
              />
              <div v-if="getImageList(post.images).length > 3" class="more-images">
                +{{ getImageList(post.images).length - 3 }}
              </div>
        </div>
        
                <div class="post-meta">
                  <el-tag :type="getCategoryType(post.category)" size="small">
                    {{ getCategoryName(post.category) }}
                  </el-tag>
              <span class="meta-time">{{ formatTime(post.createTime) }}</span>
              <span class="meta-stats">
                <el-icon><View /></el-icon> {{ post.viewCount || 0 }}
                <el-divider direction="vertical" />
                <el-icon><ChatDotRound /></el-icon> {{ post.commentCount || 0 }}
                <el-divider direction="vertical" />
                <el-icon><Star /></el-icon> {{ post.likeCount || 0 }}
              </span>
              </div>
            </div>
            
            <div class="post-actions">
            <el-button size="small" @click="viewPost(post.id)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button size="small" type="danger" @click="deletePost(post.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postAPI } from '@/api'
import { 
  Plus,
  Search,
  View,
  ChatDotRound,
  Star,
  Delete,
  Document
} from '@element-plus/icons-vue'

    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const posts = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
const selectedCategory = ref('')
    const searchKeyword = ref('')
    
    // 统计数据
    const stats = reactive({
      totalPosts: 0,
      totalViews: 0,
      totalLikes: 0,
      totalComments: 0
    })
    
// 获取当前用户ID（兼容 userId / user_id / JWT）
const getCurrentUserId = () => {
  // 1) 从 userInfo 读取
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const info = JSON.parse(userInfoStr)
      if (info && (info.userId || info.user_id)) {
        return info.userId || info.user_id
      }
    }
  } catch {}

  // 2) 从 JWT 解码
  try {
    const token = localStorage.getItem('token') || localStorage.getItem('authToken')
    if (token && token.includes('.')) {
      const payload = JSON.parse(atob(token.split('.')[1] || ''))
      if (payload && (payload.userId || payload.user_id || payload.uid || payload.id)) {
        return payload.userId || payload.user_id || payload.uid || payload.id
      }
    }
  } catch {}

  return null
}

// 图片处理 - 参考商城的 parseCoverList 函数
const getImageList = (images) => {
  // 如果为空，返回空数组
  if (!images) return []
  
  // 如果已经是数组，过滤后返回
  if (Array.isArray(images)) {
    // 检查数组第一个元素是否是对象（包含successUrls）
    if (images.length > 0 && images[0] && typeof images[0] === 'object' && images[0].successUrls) {
      return images[0].successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
    }
    return images.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
  }
  
  // 如果是字符串，尝试解析
  if (typeof images === 'string') {
    // 如果是空字符串，返回空数组
    if (!images.trim()) {
      return []
    }
    
    // 如果看起来像单个URL（以http开头），包装成数组
    if (images.startsWith('http')) {
      return [images]
    }
    
    // 尝试解析JSON字符串
    try {
      const parsed = JSON.parse(images)
      
      // 如果解析结果是数组
      if (Array.isArray(parsed)) {
        // 检查是否是 [{successUrls: [...]}] 格式
        if (parsed.length > 0 && parsed[0] && typeof parsed[0] === 'object' && parsed[0].successUrls) {
          return parsed[0].successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
        }
        // 普通URL数组
        return parsed.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
      }
      
      // 如果解析结果是对象且包含successUrls
      if (parsed && typeof parsed === 'object' && parsed.successUrls && Array.isArray(parsed.successUrls)) {
        return parsed.successUrls.filter(img => img && typeof img === 'string' && !img.startsWith('blob:'))
      }
      
      // 如果解析结果是单个URL字符串
      if (typeof parsed === 'string' && parsed) {
        return [parsed]
      }
      
      return []
    } catch (error) {
      console.warn('解析图片列表失败:', images)
      return []
    }
  }
  
  // 其他情况返回空数组
  return []
}

// 获取我的帖子
const fetchMyPosts = async () => {
  const userId = getCurrentUserId()
  
          if (!userId) {
    ElMessage.warning('请先登录')
    router.push('/userLogin')
    return
  }

  try {
    loading.value = true
    
    const response = await postAPI.getPostsByUser(userId, {
            page: currentPage.value,
      size: pageSize.value
    })

    if (response.code === 0) {
      let postList = response.data.posts || []
      // 兜底：后端若未按用户过滤，这里前端强制按 userId 过滤
      postList = postList.filter(p => String(p.userId) === String(userId))
      
      // 应用筛选
      if (selectedCategory.value) {
        postList = postList.filter(post => post.category === selectedCategory.value)
      }
      
            if (searchKeyword.value.trim()) {
              const keyword = searchKeyword.value.trim().toLowerCase()
        postList = postList.filter(post => 
                post.title.toLowerCase().includes(keyword) || 
                post.content.toLowerCase().includes(keyword)
              )
            }
            
      posts.value = postList
          total.value = response.data.total || 0
          
          // 计算统计数据
      calculateStats(postList)
        } else {
          ElMessage.error(response.message || '获取帖子列表失败')
        }
      } catch (error) {
        ElMessage.error('获取帖子列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 计算统计数据
const calculateStats = (postList) => {
  stats.totalPosts = postList.length
  stats.totalViews = postList.reduce((sum, post) => sum + (post.viewCount || 0), 0)
  stats.totalLikes = postList.reduce((sum, post) => sum + (post.likeCount || 0), 0)
  stats.totalComments = postList.reduce((sum, post) => sum + (post.commentCount || 0), 0)
    }
    
    // 查看帖子
const viewPost = (postId) => {
  router.push(`/community/post/${postId}`)
    }
    
    // 删除帖子
const deletePost = async (postId) => {
      try {
        await ElMessageBox.confirm('确定要删除这个帖子吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
    const response = await postAPI.deletePost(postId)
    
        if (response.code === 0) {
          ElMessage.success('帖子删除成功')
      await fetchMyPosts()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
// 跳转到发布页面
const goToPublish = () => {
  router.push('/community/CommunityHome')
}

// 筛选
const handleFilter = () => {
      currentPage.value = 1
      fetchMyPosts()
    }
    
// 分页
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchMyPosts()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchMyPosts()
    }
    
// 工具函数
    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
  return date.toLocaleDateString('zh-CN')
    }
    
    const getCategoryName = (category) => {
  const map = {
    fishing: '钓鱼经验',
    help: '求助问答',
    tips: '技巧分享',
    general: '综合讨论'
  }
  return map[category] || '其他'
    }
    
    const getCategoryType = (category) => {
  const map = {
    fishing: 'primary',
    help: 'warning',
    tips: 'success',
    general: 'info'
  }
  return map[category] || 'info'
}

// 页面加载
    onMounted(() => {
      fetchMyPosts()
    })
</script>

<style scoped>
.my-presentation-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-content .title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.header-content .subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px;
}

.stat-icon {
  font-size: 36px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 13px;
  color: #909399;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.posts-section {
  min-height: 400px;
}

.empty-state {
  padding: 60px 0;
}

.post-item {
  margin-bottom: 16px;
  border-radius: 12px;
  transition: all 0.3s;
}

.post-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.post-main {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.post-info {
  flex: 1;
}

.post-title {
  margin: 0 0 12px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  cursor: pointer;
  transition: color 0.3s;
}

.post-title:hover {
  color: #409eff;
}

.post-content {
  margin: 0 0 12px 0;
  color: #606266;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-thumbnails {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  cursor: pointer;
}

.more-images {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 6px;
  color: #909399;
  font-size: 14px;
  font-weight: 600;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.meta-time {
  font-size: 13px;
  color: #909399;
}

.meta-stats {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #909399;
}

.post-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-self: flex-start;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-presentation-container {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-content .title {
    font-size: 22px;
  }

  .post-main {
    flex-direction: column;
  }
  
  .post-actions {
    flex-direction: row;
    align-self: stretch;
  }

  .thumbnail {
    width: 60px;
    height: 60px;
  }

  .more-images {
    width: 60px;
    height: 60px;
  }
}
</style>
